package com.hantang.web.json.handlers;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;

import com.google.gson.Gson;
import com.hantang.web.config.JsonConfig;
import com.hantang.web.dao.ArticleDao;
import com.hantang.web.data.ArticleData;
import com.hantang.web.json.ds.Article;
import com.hantang.web.json.ds.MetaData;
import com.hantang.web.json.res.ArticleInfoRes;

public class QueryArticlesHandler extends AbstractHandler {

	static String META_INFO = "content max size is" + JsonConfig.getInstance().articleInfoContentSize;
	private static Logger logger = Logger.getLogger(QueryArticlesHandler.class);
	@Override
	public String doService(Request req, Response resp) throws Exception {

		String slastUpdatetime = req.getParameter("lastupdatetime");
		String scount = req.getParameter("count");
		
		String sret = handleServlet(slastUpdatetime, scount);
		
		return sret	;
	}

	public static String handleServlet(String slastUpdatetime, String scount) {
		Date lastUpdateTime = new Date(Long.MAX_VALUE);
		if(slastUpdatetime != null)
		{
			lastUpdateTime = new Date(Long.valueOf(slastUpdatetime));
		}
		
		int count = 10;
		if(scount != null){
			count = Integer.valueOf(scount.trim());
		}
		List<Article> articles = handle(lastUpdateTime, count);
		
		ArticleInfoRes resData = new ArticleInfoRes();
		resData.setData(articles);
		resData.setMeta(new MetaData(MetaData.META_DATA_SUCCESS_CODE, META_INFO));
		Gson gson = new Gson();
		String sret = gson.toJson(resData);
		return sret;
	}

	public static List<Article> handle(Date lasttime, int count)
	{
		logger.info("handle, lasttime:" + lasttime + " count:" + count);
		List<Article> articles = new ArrayList<Article>();
		ArticleDao dao = new ArticleDao();
		List<ArticleData> datas = dao.queryDatas(lasttime, count);
		for(ArticleData data : datas)
		{
			Article article = Article.convertData2Json(data, JsonConfig.getInstance().articleInfoContentSize);
			articles.add(article);
		}
		logger.info("handle, lasttime:" + lasttime + " return size:" + articles.size());
		return articles;		
	}
	
	
	
	
	
}
